package com.gali.leetcode.day11;

/**
 * @Auther: gali
 * @Date: 2022-07-25 17:24
 * @Description:
 */
public class Solution {
    /**
     * 搜索旋转排序数组----二分查找
     * @param nums
     * @param target
     * @return
     */
    public int search(int[] nums, int target) {
        int length = nums.length;
        if (length<=0){
            return -1;
        }
        if (length==1){
            return nums[0]==target?0:-1;
        }
        int l = 0;
        int r = length - 1;
        while (l<=r){
            int mid=(l+r)/2;
            if (nums[mid]==target){
                return mid;
            }
            if (nums[0]<=nums[mid]){
                if (nums[0]<=target&&nums[mid]>target){
                    r=mid-1;
                }else {
                    l=mid+1;
                }
            }else {
                if (nums[mid] < target && target <= nums[length - 1]) {
                    l = mid + 1;
                } else {
                    r = mid - 1;
                }
            }
        }
        return -1;
    }

    /**
     * 在排序数组中查找元素的第一个和最后一个位置---二分查找
     * @param nums
     * @param target
     * @return
     */
        public int[] searchRange(int[] nums, int target) {
            int leftIdx = binarySearch(nums, target, true);
            int rightIdx = binarySearch(nums, target, false) - 1;
            if (leftIdx <= rightIdx && rightIdx < nums.length && nums[leftIdx] == target && nums[rightIdx] == target) {
                return new int[]{leftIdx, rightIdx};
            }
            return new int[]{-1, -1};
        }

        //二分查找
        private int binarySearch(int[] nums, int target, boolean lower) {
            int left = 0, right = nums.length - 1, ans = nums.length;
            while (left <= right) {
                int mid = (left + right) / 2;
                if (nums[mid] > target || (lower && nums[mid] >= target)) {
                    right = mid - 1;
                    ans = mid;
                } else {
                    left = mid + 1;
                }
            }
            return ans;
        }
}
